<?php
namespace app\common\model\cost;

use think\Model;
use think\facade\Session;
use app\common\model\user\User;
use app\common\model\cost\Costtype;

class Revenue extends Model
{
     // 设置当前模型对应的完整数据表名称
        protected $table = 'revenue';
        protected $pk = 'RevenueId';
        
        const STATEINT = 1;
        const STATEOK  = 1;//已处理
        const STATENO  = 2;//已失效
        const STATEDELETE = 404;//被删除的订单
    public function typeinfo(){
         return $this->hasOne('app\common\model\cost\Costtype','TypeId','TypeId');
    }

     /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1=>'全部',1=>'已生效',2=>'已失效'];
        if($value!==''){
            return $status[$value];
        }
        return $status;
    }

    /**
     * 增加收入
     * @param  [type] $idata [description]
     * @return [type]        [description]
     */
    public static function screate($idata){
        $userinfo = User::getinfo();
        //基础信息
        $data['State'] = Revenue::STATEINT;
        $data['TypeId'] = $idata['TypeId'];
        if(!empty($idata['UpImg'])){
            $data['UpImg']  = $idata['UpImg'];
        }
        $data['PayTime'] = $idata['PayTime'];
        $data['PayCost'] = $idata['PayCost'];
        if(!empty($idata['RelationUserId'])){
            $data['RelationUserId'] = $idata['RelationUserId'];
        }
        
        if(!empty($idata['RelationListId'])){
            $data['RelationListId'] = $idata['RelationListId'];
        }
        if(!empty($idata['UpNote'])){
            $data['UpNote'] = $idata['UpNote'];
        }
        $data['UpTime'] = date('Y-m-d H:i',time());
        $data['UpUserId'] = $userinfo->UserId;
        $ReceiptList = Revenue::create($data);
        Costjournal::add_cost($data['PayTime'],$data['TypeId'],$data['PayCost']);
        return sok('成功记录一笔收入');
    }

    /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data,$type = 'hawa',$is_page = true){

        $rdata = Revenue::where('State','<>',Revenue::STATEDELETE);
        $userinfo = User::getinfo();
    
        if($type=='acco'||$type=='mana'){
            $rdata = $rdata->with(['typeinfo']);
            $visible = ['TypeId','RevenueId','State','PayTime','PayCost','UpTime','typeinfo.TypeTable','typeinfo.TypeName'];
        }else if($type=='summary'){
            $data['field'] = ['TypeId','RevenueId as id','State','PayTime','PayCost','UpTime'];
        }else{
            $rdata = $rdata->where('RelationUserId',Pub::userid());
            $rdata = $rdata->with(['typeinfo']);
            $visible = ['TypeId','RevenueId','State','PayTime','PayCost','UpTime','typeinfo.TypeTable','typeinfo.TypeName'];
        }

        $option = come_model_option($data,$rdata,$is_page);
        $rdata = $option['rdata'];
        $data = $option['data'];
  
        $rdata = $rdata->select();
        if(!empty($visible)){
            $visible = array_merge(['RevenueId'],$visible);
            $rdata =  $rdata->visible($visible);
        }

        $ndata['list'] = $rdata->toArray();
        $ndata['statetext'] = Revenue::getStatusText();
        if($is_page){
            $ndata['pageinfo'] = ['pageindex'=>$data['pageindex'],'pagemax'=>$data['count']];
        }
        return $ndata;
    }


    /**
     * 判断列表中的产品状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function list_state($id,$hidden=[],$hidloag=true){
        $data = Revenue::get($id);
        if(empty($data)){
            return moerr('没有找到您需要的信息');
        }else{
            if($hidloag){
                $hidden= array_merge(['OperationLog'],$hidden);
                $data = $data->hidden($hidden)->toArray();
            }elseif(empty($hidden)){
                $data = $data->toArray();
            }else{
                $data = $data->hidden($hidden)->toArray();    
            }
            return sok($data);
        }
    }
    
     /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id,$type='aooc'){
        if($type=='acco'){
            $data = self::list_state($id,[]);
        }elseif($type=='mana'){
            $data = self::list_state($id,[],false);
        }elseif($type=='costview'){
            $data = self::list_state($id,[],false);
        }else{
            return moerr('参数错误');
        }
        if (!$data['code']) { return $data; }
        $rdata = $data['msg'];
        $rdata['Statetext'] = self::getStatusText($rdata['State']);
        $rdata['upinfo'] = User::getpublicinfo($rdata['UpUserId']);
        $rdata['typeinfo'] = Costtype::getinfo($rdata['TypeId']);
        if(!empty($rdata['RelationUserId'])){
            $rdata['userinfo'] = User::getpublicinfo($rdata['RelationUserId']);
        }
        // $rdata['StateList'] = DeliveryList::STATEARRAY;
        return ['code'=>true,'msg'=>$rdata]; 
    }

   /**
    * 用户修改信息
    * @param  [type]  $data   [description]
    * @param  boolean $wtnote [是否记录]
    * @return [type]          [description]
    */
    public static function user_reinfo($data,$wtnote=true){
        if(empty($data['id'])){
            return moerr('缺少重要参数');
        }
        $info = Revenue::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo = empty($info->OperationLog)?'':$info->OperationLog."\n";
        $reinfo = $reinfo .'【' .$userinfo->Name.'|'.$userinfo->UserId.'】在'.date('Y-m-d H:i',time()).'进行了信息调整：';
        $nreinfo = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if(empty($sb)){
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if($key=='State'&&$value!==$ovalue){
                $ndata['TypeId'] = Costtype::getid('cost');
                $ndata['PayTime'] = date('Y-m-d H:i',time());
                $ndata['RelationListId'] = $data['id'];
                if ((int)$value==Revenue::STATEOK) {
                    if(date("Ymd",time())!==date("Ymd",strtotime($info['PayTime']))){
                        $ndata['PayCost'] = $info['PayCost'];
                        Revenue::screate($ndata);
                    }
                    //修改统计
                    Costjournal::re_cost($info['PayTime'],$info['TypeId'],$info['PayCost']);
                }
                if((int)$value==Revenue::STATENO) {
                    if(date("Ymd",time())!==date("Ymd",strtotime($info['PayTime']))){
                        $ndata['PayCost'] = $info['PayCost'];
                        Pay::screate($ndata);
                    }
                    //修改统计 取消订单的统计费用
                    Costjournal::re_cost($info['PayTime'],$info['TypeId'],$info['PayCost']);
                }
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value = $info->getStatusText((int)$value);
                $ovalue = $info->getStatusText((int)$ovalue);
                $nreinfo =  $nreinfo . '字段【'.$info->getfiledname($key).'】由【'.  $ovalue .'】修改为【' .$value.'】;'."\n";
            }else if(!empty($value)&&$ovalue !== $value){
                $nreinfo =  $nreinfo . '字段【'.$info->getfiledname($key).'】由【'.  $ovalue .'】修改为【' .$value.'】;'."\n";
                $info->$key = $value;
            }
        }
        if(!empty($nreinfo)){
            if($wtnote){
                $reinfo = $reinfo ."\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        }else{
            return moerr('没有找到需要调整的数据');
        }
    }

     public static function getfiledname($str){
        $filename = ['TypeId'=>'费用分类','State'=>'状态',
                 'PayTime'=>'支出时间','PayCost'=>'支出金额','RelationUserId'=>'涉及用户id',
                 'RelationListId'=>'涉及订单id','UpNote'=>'记录时间','UpImg'=>'涉及图片'];
        if(empty($filename[$str])){
            return false;
        }
        return $filename[$str];
    }
}
